<template>
  <div>
    <!-- 菜单管理 -->
    <el-card class="menu-card" v-loading="loading">
      <el-button class="menu-button" type="success" icon="el-icon-edit" size="mini" style="float:right"
        @click="addMenu">添加菜单</el-button>
      <el-table highlight-current-row header-align='center' align='center' class='menu-table' :data="MenuList"
        style="width: 100%" row-key="id" default-expand-all :tree-props="{children: 'childs', hasChildren: 'is_point'}">
        <el-table-column label="标题" ref="menus" width="180">
          <template v-slot={row}>
            <i :class="row.icon" id='menu-icon'></i>
            <span>{{row.title}}</span>
            <!-- <span>{{MenuList}}</span> -->
          </template>
        </el-table-column>
        <el-table-column align='left' prop="code" label="权限点代码">
        </el-table-column>
        <el-table-column align='center' label="操作" width="180">
          <template v-slot={row}>
            <el-button type="primary" icon="el-icon-edit" circle size="small" plain @click="editMenu(row)"></el-button>
            <el-button type="danger" @click="del(row)" icon="el-icon-delete" circle size="small" plain></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加菜单对话框 -->
    <el-dialog title="创建菜单" :visible.sync="addMenuVisible" width="840px" :before-close="addhandleClose">
      <el-form :model="addform" class="addform" ref="refaddform" :rules="ruleadd">
        <el-form-item label="权限组名称" center>
          <el-radio-group v-model="radio" @change="changeHandler">
            <el-radio :label="0">菜单</el-radio>
            <el-radio :label="1">权限点</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限组名称">
          <el-select v-model="treeDataValue.title" placeholder="请选择" @change="selectChange" visible-change blur
            ref='selref' @focus="render">
            <el-option :value="addform.title" :disabled="false" style="height: 100%">
              <el-tree :expand-on-click-node="false" style="width:auto" ref="tree" :data="rend"
                :highlight-current='true' :default-expand-all='true' :default-checked-keys="[actionId]" node-key="id"
                :props="defaultProps" @node-click="handleNodeClick">
              </el-tree>
            </el-option>
          </el-select>
        </el-form-item>
        <div>
          <el-form-item label="权限代码" label-width='120px' prop="code" class="addinput">
            <el-input v-model="addform.code"></el-input>
          </el-form-item>
          <el-form-item label="权限标题" label-width='120px' prop="title" class="addinput">
            <el-input v-model="addform.title"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addMenuVisible = false">取 消</el-button>
        <el-button type="primary" @click="addsubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加菜单对话框  end-->

    <!-- 修改菜单对话框  start-->
    <el-dialog title="修改菜单" :visible.sync="editMenuVisible" width="840px" :before-close="edithandleClose">
      <el-form :model="editform" class="addform" ref="refeditform" :rules="ruleedit">
        <el-radio-group v-model="radio" disabled class="editD">
          <el-radio :label="0">菜单</el-radio>
          <el-radio :label="1">权限点</el-radio>
        </el-radio-group>
        <el-form-item label="权限组名称">
          <el-select v-model="rowtitle.title" placeholder="请选择" disabled>
            <el-option :value="rowtitle.title" :disabled="false" style="height: 100%">
              <el-tree class='disabledCss' :expand-on-click-node="false" style="width:auto" ref="tree" :data="rend"
                highlight-current :default-expand-all='true' node-key="id" :props="defaultProps"
                :default-checked-keys="[33]" @node-click="handleNodeClick">
              </el-tree>
            </el-option>
          </el-select>
        </el-form-item>
        <div>
          <el-form-item label="权限代码" label-width='120px' prop="code" class="addinput">
            <el-input v-model="editform.code"></el-input>
          </el-form-item>
          <el-form-item label="权限标题" label-width='120px' prop="title" class="addinput">
            <el-input v-model="editform.title"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editMenuVisible = false">取 消</el-button>
        <el-button type="primary" @click="editsubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加菜单对话框  end-->

  </div>
</template>

<script>
import { list, remove, add, update } from '../../api/base/menus.js'
console.log(document.querySelector('el-icon-arrow-right'))
export default {
  data () {
    return {

      selectData: [], // 下拉框中的选项数据
      actionId: 1,
      defaultProps: {
        children: 'childs',
        label: 'title'
      },
      rowtitle: {
        title: ''
      },
      treeDataValue: {
        title: '主导航'
      },
      radio: 0,
      ruleadd: {
        title: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      ruleedit: {
        title: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      qClass: ['el-icon-view', 'el-icon-document', 'el-icon-folder-opened'],
      editform: [],
      oneList: [],
      zeroList: [],
      editform: {
        is_point: '',
        code: '',
        id: '',
        pid: '',
        title: ''
      },
      editMenuVisible: false,
      addform: {
        is_point: '',
        code: '',
        id: '',
        pid: '',
        title: ''
      },
      addMenuVisible: false,
      menuList: [],
      MenuList: [],
      loading: true
    }
  },
  computed: {
    disabledFn () {

    },
    rend () {
      if (this.radio == 0) {
        return this.zeroList
      } else if (this.radio == 1) {
        return this.oneList
      }
    }
  },
  mounted () {

  },
  created () {
    this.getMenuList()
  },

  methods: {
    render () {
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.actionId)
      })
    },
    selectChange (data) {

    },
    changeHandler (value) {
      console.log(value)
      this.actionId = 1
      if (value) { this.addform.code = '' }
      this.addform.title = ''
      this.addform.pid = null
      if (this.addform.code.lengh != 0 || this.addform.title.length != 0) {
        this.addform.code = ''
        this.addform.title = ''
        this.addform.pid = null
        this.treeDataValue.title = '主导航'
      }

      //  活跃选中数组为空
    },
    async editsubmit () {
      this.$refs.refeditform.validate(async bool => {
        if (!bool) return this.$message.error('不能为空')
        this.editMenuVisible = false
        await update(this.editform)
        this.getMenuList()
      })
    },
    async addsubmit () {
      this.$refs.refaddform.validate(async bool => {
        if (!bool) return this.$message.error('不能为空')
        this.addMenuVisible = false
        this.addform.pid = this.treeDataValue.pid
        if (!this.treeDataValue.is_point && this.radio == 0) {
          this.addform.is_point = false
        } else {
          this.addform.is_point = true
        }
        if (this.radio == 0) {
          this.addform.is_point = false
        } else {
          this.addform.is_point = true
        }
        const res = await add(this.addform)
        this.getMenuList()
        if (res) {
          this.addform.code = ''
          this.addform.title = ''
          if (this.radio == 0) {
            this.addform.is_point = false
          } else {
            this.addform.is_point = true
          }
          this.addform.id = ''
          this.addform.pid = '主导航'
          this.radio = 0
          this.treeDataValue.title = ''
        }
      })
    },
    handleNodeClick (obj, node, self) {
      console.log(obj)
      this.$refs.selref.toggleMenu()

      this.treeDataValue.title = obj.title
      this.treeDataValue.pid = this.treeDataValue.id
      this.actionId = obj.id
    },
    async del (row) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      await remove(row)
      this.getMenuList()
      this.$message.success('成功')
    },
    editMenu (row) {
      console.log(row)
      this.editMenuVisible = true
      this.editform.code = row.code
      this.editform.title = row.title
      this.editform.id = row.id
      this.editform.is_point = row.is_point
      this.rowtitle.title = row.title
      if (this.editform.pid == null) {
        this.editform.pid = row.id
      } else {
        this.editform.pid = row.pid
      }
      if (!row.is_point) {
        this.editform.is_point = false
      }
      if (this.editform.is_point) {
        this.radio = 1
      } else {
        this.radio = 0
      }
      console.log(this.editform)
    },
    edithandleClose () {
      this.editMenuVisible = false
    },
    addhandleClose () {
      this.addMenuVisible = false
    },
    addMenu () {
      this.addMenuVisible = true
      this.treeDataValue.title = '主导航'
    },
    async getMenuList () {
      const { data: res } = await list()
      if (res.length != 0) {
        this.menuList = res
        this.loading = false
      }

      // 深拷贝数组
      const newMenuList = JSON.parse(JSON.stringify(this.menuList))
      //  处理菜单数据 母数组
      const optlist = JSON.parse(JSON.stringify(this.menuList))
      const newMenuList1 = JSON.parse(JSON.stringify(newMenuList))
      // 修改返回值key
      var keyMap = {
        points: 'childs'
      }
      for (var i of newMenuList) {
        for (var j in i) {
          var p = keyMap[j]
          if (p) {
            i[p] = i[j]
            delete i[j]
            for (var k of i[p]) {
              for (var l in k) {
                var newKey = keyMap[l]
                if (newKey) {
                  k[newKey] = k[l]
                  delete k[l]
                }
              }
            }
          }
        }
      }
      this.MenuList = newMenuList
      for (var first of this.MenuList) {
        var iClass = ['el-icon-view', 'el-icon-document', 'el-icon-folder-opened']
        for (var i in first) {
          first.icon = iClass[(iClass.length - 1)]
          if (Array.isArray(first[i])) {
            for (var second of first[i]) {
              second.icon = iClass[(iClass.length - 2)]
              for (var j in second) {
                if (Array.isArray(second[j])) {
                  for (var third of second[j]) {
                    for (var k in third) {
                      var mm = {
                        is_point: 'is_point'
                      }
                      var p = mm[k]
                      if (third[p]) {
                        third.icon = iClass[(iClass.length - 3)]
                      } else {
                        third.icon = iClass[(iClass.length - 2)]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
      //  console.log(this.MenuList);

      // 处理菜单数据 去掉points

      const handleClose = () => {
        const list = optlist.map(item => {
          if (item.childs) {
            item.childs.map(v => {
              if (v.points) {
                v.points = []
              }
              return v
            })
          }
          return item
        })
        return list
      }
      var a = handleClose()

      for (var i of a) {
        for (var j in i) {
          var p = keyMap[j]
          if (p) {
            i[p] = i[j]
            delete i[j]
            for (var k of i[p]) {
              for (var l in k) {
                var newKey = keyMap[l]
                if (newKey) {
                  k[newKey] = k[l]
                  delete k[l]
                }
              }
            }
          }
        }
      }

      var arr3 = {}
      var arr2 = []
      arr3.childs = a
      arr3.id = 1
      arr3.pid = 999
      arr3.title = '主导航'
      arr3.code = ''
      arr2.push(arr3)
      this.zeroList = arr2

      var arr = {}
      var arr1 = []
      arr.childs = a
      arr.id = 1
      arr.pid = 999
      arr.title = '主导航'
      arr.code = ''
      console.log(arr)
      arr.childs.forEach(item => item.disabled = true)
      arr1.push(arr)
      this.oneList = arr1
      console.log(this.oneList)
      //  function deepClone(source) {
      //           const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
      //           for (let keys in source) { // 遍历目标
      //           console.log(keys);
      //               if (source[keys] && typeof source[keys] === 'object' && keys=='childs') { // 如果值是对象或者数组，就递归一下
      //                   targetObj[keys] = deepClone(source[keys]);
      //               } else { // 如果不是，就直接赋值
      //                   targetObj[keys] = source[keys];

      //               }
      //           }
      //           return targetObj;
      //       }

      // console.log(this.MenuList);

      // function f(item ) {
      //                 for( var i in item ) {
      //                         if(i == 'is_point'){
      //                             i = 'disabled'

      //                         }
      //                       if ( typeof item[i] === "object" ) {
      //                       f (item[i]);
      //                     }
      //                   }

      //                 }
      //             f(arr3)
      // console.log(arr3);

      // 渲染添加icon
    }
  }
}

</script>

<style scoped lang='less'>
/deep/.disabledCss {
  pointer-events: none;
}
/deep/.el-tree-node__content {
  pointer-events: none !important;
}
/deep/ .menu-card {
  margin: 20px 20px;
}
.menu-button {
  text-align: center;
  margin-bottom: 20px;
}
.menu-table {
  margin-top: 40px;
}
#menu-icon {
  margin-left: 0px;
  margin-right: 5px;
  font-size: 16px;
}
.el-table/deep/.el-table__expand-icon--expanded {
  width: 0px !important;
  height: 0px !important;
  display: none !important;
}
// 未展开
.el-table/deep/ .el-icon-arrow-right:before {
  display: none;
}
// 展开
// .el-table/deep/ .el-table__expand-icon--expanded {
// el-table__expand-icon
//   .el-icon-arrow-right:before {
//     content: "\e706";
//     display: block;
//     width: 15px;
//     height: 20px;
//     font-size: 18px;
//     background-size: 21px;
//   }
// }
.el-table/deep/.el-table__placeholder {
  width: 0px !important;
}
.addform {
  width: 400px;
  margin-left: 120px;
}
.addinput {
  margin-left: -40px;
}
/deep/.el-select-dropdown__item {
  width: 197px !important;
}
.el-select-dropdown__item.selected {
  font-weight: 400;
}
/deep/.el-tree-node__content > .el-tree-node__expand-icon {
  width: 0px;
  height: 0px;
  padding: 0;
  margin: 14px;
}
// /deep/.el-tree-node__expand-icon.el-icon-caret-right{
//   width: 0px;
//   height: 0px;
// }
/deep/.el-tree .el-tree--highlight-current {
  margin-left: 40px;
}
/deep/.el-icon-caret-right:before {
  display: none;
}
.el-select-dropdown__item {
  padding: 0px;
}
.editD {
  margin-bottom: 20px;
}
</style>
